const Service = require('egg').Service;
class OrderService extends Service {
    get Order() {
        return this.app.model.Order
    }
    get UserOrder() {
        return this.app.model.UserOrder
    }
    //创建订单
    async createOrder(data) {
        const order = await this.Order(Object.assign({}, data, { create_by_id: this.ctx.userId })).save()
        return Promise.resolve(order)
    }
    //获取订单
    async getOrders(data) {
        let orders = await this.Order.find({ data })
        if (this.ctx.userId) {
            let userOrder = await this.UserOrder.findOne({ user: this.ctx.userId });
            if (userOrder && userOrder.orders) {
                orders = orders.map(item => Object.assign({}, item["_doc"], { my_status: userOrder.orders.includes(item["_id"]) ? 1 : 0 }))
            } else {
                orders = orders.map(item => Object.assign({}, item["_doc"], { my_status: 0 }))
            }
        }
        return Promise.resolve(orders)
    }
    //获取订单详情
    async getOrderById() {
        let order = await this.Order.findById(this.ctx.params.id)
        if (this.ctx.userId) {
            let userOrder = await this.UserOrder.findOne({ user: this.ctx.userId });
            if (userOrder && userOrder.orders && userOrder.orders.includes(order["_id"])) {
                order = Object.assign({}, order["_doc"], { my_status: 1 })

            } else {
                order = Object.assign({}, order["_doc"], { my_status: 0 })
            }
        }
        return Promise.resolve(order)
    }
    //获取当前登录用户的订单
    async getMyOrders() {
        const userId = this.ctx.userId;
        const params = this.ctx.request.query;
        let userOrder = await this.UserOrder.findOne({ user: userId });
        let result = []
        if (userOrder && userOrder.orders) {
            while (userOrder.orders.length > 0) {
                const id = userOrder.orders.pop()
                const order = await this.Order.findOne({ _id: id, })
                result.push(order)
            }
        }
        if (userId) {
            let userOrder = await this.UserOrder.findOne({ user: this.ctx.userId });
            if (userOrder && userOrder.orders) {
                result = result.map(item => Object.assign({}, item["_doc"], { my_status: userOrder.orders.includes(item["_id"]) ? 1 : 0 }))
            } else {
                result = result.map(item => Object.assign({}, item["_doc"], { my_status: 0 }))
            }
        }
        return Promise.resolve(result)
    }

}

module.exports = OrderService;
